package com.zh.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.seckill.constant.UserConstant;
import com.zh.seckill.exception.GlobalException;
import com.zh.seckill.mapper.UserMapper;
import com.zh.seckill.pojo.User;
import com.zh.seckill.service.UserService;
import com.zh.seckill.utils.CookieUtil;
import com.zh.seckill.utils.MD5Util;
import com.zh.seckill.utils.UUIDUtil;
import com.zh.seckill.vo.LoginVo;
import com.zh.seckill.vo.R;
import com.zh.seckill.vo.RespEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhanghuan
 * @since 2022-03-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public R doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        // if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
        //     return R.error(RespEnum.LOGIN_ERROR);
        // }
        // if (!ValidatorUtil.isMobile(mobile)) {
        //     return R.error(RespEnum.MOBILE_ERROR);
        // }

        User user = userMapper.selectById(mobile);
        if (user == null) {
            throw new GlobalException(RespEnum.LOGIN_ERROR);
        }
        // 判断密码是否正确
        if (!MD5Util.fromPassToDBPass(password, user.getSalt()).equals(user.getPassword())) {
            throw new GlobalException(RespEnum.LOGIN_ERROR);
        }
        //生成cookie
        String ticket = UUIDUtil.uuid();
        // request.getSession().setAttribute(ticket, user);
        // 将用户信息存入redis
        redisTemplate.opsForValue().set(UserConstant.USERTICKET_PREFX + ticket, user);
        CookieUtil.setCookie(request, response, "userTicket", ticket);

        return R.success();
    }

    @Override
    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(userTicket)) {
            return null;
        }
        User user = (User) redisTemplate.opsForValue().get(UserConstant.USERTICKET_PREFX + userTicket);
        return user;
    }
}
